package org.jeecg.modules.iot.common;

import lombok.Data;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.iot.tools.HttpServletUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;


@Data
@Component
@Configuration
@ConfigurationProperties(prefix = "iot")
public class AppConfig {

    private String accessKeyId;

    private String accessKeySecret;

    private String productKey;

    private String regionId;

    private String mnsEndpoint;

    public String getAccessKeyId() {
        return accessKeyId;
    }

    public String getAccessKeySecret() {
        return accessKeySecret;
    }

    public String getProductKey() {
        return productKey;
    }

    public String getRegionId() {
        return regionId;
    }

    public String getMnsEndpoint() {
        return mnsEndpoint;
    }

    public String[] getMachines(){
        String path = HttpServletUtils.getHttpServletRequest().getServletContext().
                getRealPath("/WEB-INF/classes/machines.properties");

        List<String> machines = new ArrayList<>();
        BufferedReader bufferedReader = null;
        try {
            bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF-8"));
            String str = null;
            while((str = bufferedReader.readLine()) != null){
                if(StringUtils.isNotBlank(str)){
                    machines.add(str);
                }
            }
            bufferedReader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if(bufferedReader != null){
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        String[] data = machines.toArray(new String[machines.size()]);
        ArrayUtils.reverse(data);
        return data;
    }
}
